﻿#region License
/* Copyright (c) 2011 Maksymilian Mulawa
	
Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice, 
 * this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the documentation 
 * and/or other materials provided with the distribution.
   3. The name of the author may not be used to endorse or promote products 
 * derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using ReplicationExplorer.DomainModel.Distributor;
using ReplicationExplorer.DomainModel.Distributor.Entities;

namespace ReplicationExplorer
{
    /// <summary>
    /// Interaction logic for ConnectDialog.xaml
    /// </summary>
    public partial class ConnectDialog : Window
    {
        public ConnectDialog()
        {
            InitializeComponent();

            cbServerName.ItemsSource = Properties.Settings.Default.DistributorList ?? new StringCollection();
        }

        public SqlServerInfo ServerInfo { get; set; }
        public UserCredentials User { get; set; }
        public DistributorServer Distributor { get; set; }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            string selectedServer = GetSelectedServer();
            if(string.IsNullOrEmpty(selectedServer))
            {
                MessageBox.Show("Enter Distributor server name", "Distributor server name missing", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                e.Handled = true;
            }
            else if(!IsWindowsAuthenticationSelected() && string.IsNullOrEmpty(tbUserName.Text))
            {
                MessageBox.Show("When using Sql Authentication please enter User name", "Username is empty.", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                e.Handled = true;
            }
            else
            {
                UserCredentials userCredentials = new UserCredentials();
                userCredentials.UserId = tbUserName.Text;
                userCredentials.Password = tbPassword.Password;
                userCredentials.IsWindowsAuthenticated = IsWindowsAuthenticationSelected();
                User = userCredentials;
                ServerInfo = new SqlServerInfo { ServerName = selectedServer };
                DistributorSession session = new DistributorSession(User, ServerInfo);
                DistributorServer distributorServer = null;
                try
                {
                    distributorServer = session.GetDistributor();
                }
                catch (Exception exception)
                {
                    MessageBox.Show(string.Format("Problem occured when connecting to Distributor server\n. Connection failed with following error: \n {0}", exception.Message)
                        , "Cannot connect to Distributor server.", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    e.Handled = true;
                }

                if (distributorServer != null)
                {
                    if(!distributorServer.ServerVersion.IsSqlServer2005OrHigher)
                    {
                        MessageBox.Show(string.Format("Replication Explorer can only connect to Sql Server instances running Microsoft Sql Server 2005 or higher."),
                            "Sql Server intance should be running Sql Server 2005 or higher.", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                    else if (!distributorServer.IsDistributorLocallyInstalled)
                    {
                        MessageBox.Show(string.Format("{0} server is not a distributor.", ServerInfo.ServerName),
                            "Server is not a Distributor.", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                    else
                    {
                        Distributor = distributorServer;
                        DialogResult = true;    
                    }
                }
            }
        }
        
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void authenticationType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sqlAuthenticationCredentials != null)
            {
                bool isWindowsAuthenticationSelected = IsWindowsAuthenticationSelected();
                sqlAuthenticationCredentials.Visibility = isWindowsAuthenticationSelected ? 
                    Visibility.Hidden : 
                    Visibility.Visible;
            }
        }

        private string GetSelectedServer()
        {
            string serverName = string.Empty;

            if (!(string.IsNullOrEmpty(cbServerName.Text)))
            {
                serverName = cbServerName.Text;
            }
            else
            {
                object selectedItem = cbServerName.SelectedValue;
                if(selectedItem != null)
                {
                    serverName = selectedItem.ToString();
                }
            }   

            return serverName;
        }

        private bool IsWindowsAuthenticationSelected()
        {
            string selectedAuthenticationType = ((ComboBoxItem) ((authenticationType.SelectedValue))).Content.ToString();
            return selectedAuthenticationType.Equals("Windows Authentication", StringComparison.InvariantCultureIgnoreCase);
        }

    }
}
